#include <Network/NetworkSubsystem.h>
#include <Poco/Util/Application.h>
#include <Poco/Net/ServerSocket.h>
#include <Poco/Net/HTTPServerParams.h>
#include <Poco/NObserver.h>
#include <Poco/URIStreamOpener.h>
#include <Poco/Net/HTTPStreamFactory.h>
//#include <Poco/Net/SecureServerSocket.h>


#include <Network/RootRequestHandlerFactory.h>
#include <ApplicationStartingNotification.h>



using namespace Network;
using namespace Poco::Util;
const std::string KHaProxyForwardIPKey = "X-Forwarded-For";

NetworkSubsystem::NetworkSubsystem(void)
{
}

NetworkSubsystem::~NetworkSubsystem(void)
{
}

void NetworkSubsystem::OnStart(Application& app) 
{

	unsigned short port = (unsigned short) app.config().getInt("RootHTTPServer.port", 9980);

	// set-up a server socket
	Poco::Net::ServerSocket svs(port);
	// set-up a HTTPServer instance

	CRootRequestHandlerFactory* aFactory = new CRootRequestHandlerFactory;
	aFactory->Setup( app.config().createView("NetworkSubsystem.RequestFactory") );

	iRootServer = new Poco::Net::HTTPServer( aFactory  , svs , new Poco::Net::HTTPServerParams );
	iRootServer->start();



	////// SSL server
	//Poco::Net::SecureServerSocket aSSlSocket(9982);
	//aFactory = new CRootRequestHandlerFactory;
	//aFactory->Setup( app.config().createView("NetworkSubsystem.RequestFactory") );
	//iRootSSLServer = new Poco::Net::HTTPServer(aFactory , aSSlSocket , new Poco::Net::HTTPServerParams );
	//iRootSSLServer->start();

	////
	try
	{
		Poco::Net::HTTPStreamFactory::registerFactory();
	}
	catch (...)
	{
		
	}
	

}
/// Initializes the subsystem.

void NetworkSubsystem::OnStop() 
{
	if (iRootServer)
	{
		iRootServer->stop();
		iRootServer= NULL;
	}

	if (iRootSSLServer)
	{
		iRootSSLServer->stop();
		iRootSSLServer = NULL;
	}
}

